import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { notification, Modal } from 'ant-design-vue'
const baseURL = process.env.VUE_APP_API_BASE_URL
// 创建 axios 实例
const service = axios.create({
  baseURL: baseURL, // api base_url
  timeout: 15000 // 请求超时时间
})

let isShowModal = false
const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      if (data.code === 2111) {
        if (!isShowModal) {
          Modal.info({
            title: '错误',
            content: '你的账号已在其它设备或其它浏览器中登录，如非本人操作建议登录后修改密码',
            onOk () {
              window.sessionStorage.removeItem('pro__Access-Token')
              router.go(0)
            }
          })
        }
        isShowModal = true
        return
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(service)
  }
}

export {
  service as axios
}
